#include "socket.h"
#include "qtcpsocket.h"
#include "ui_socket.h"
#include <QDebug>
#include <QFile>

socket::socket(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::socket)
{
    ui->setupUi(this);

}

socket::~socket()
{
    delete ui;
}

socket::HttpServer(QObject *parent) : QObject(parent)
{
    server = new QTcpServer(this);
    socket = new QTcpSocket(this);

    if(!server->listen(QHostAddress::Any, 8080))
    {
        qDebug() << "Web服务未启动";
    }
    else
    {
        qDebug() << "Web服务在端口8080等待客户端连接";
    }
    //有客户端连接时触发newConnection信号
    connect(server, &QTcpServer::newConnection, this, &HttpServer::connection);

}

void socket::connection()
{
    //取出建立好连接的套接字
    socket = server->nextPendingConnection();
    //获取对方的IP和端口
    QString ip = socket->peerAddress().toString();
    qint16 port = socket->peerPort();
    QString temp = QString("[%1 : %2]: 成功连接").arg(ip).arg(port);
    qDebug() << temp;

    connect(socket,&QTcpSocket::readyRead,this,&HttpServer::onReadyRead);
}

void socket::onReadyRead()
{
    QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender());

    if(socket)
    {
        //从通信套接字中取出内容
        QByteArray array = socket->readAll();
        QString request = QString::fromUtf8(array);
        qDebug() << "正在从浏览器读取数据= " << request;

        if(request.startsWith("GET"))//如果是GET请求
        {
            QFile file("/Users/Administrator/Documents/http_demo/index.txt");
            if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
            {
                qDebug() << "文件打开失败";
                return;
            }
            QString tempStr = "";//临时字符串
            while (!file.atEnd())//判断是否读到文件末尾，如果已经达到末尾，返回 true，否则返回 false。
            {
                //tempStr = file.readLine();  //读取文件中一行
                tempStr = file.readAll();   //读取文件中所有内容
                //qDebug() <<"tempStr = "<<tempStr;
            }

            char *ch = tempStr.toLatin1().data();

            socket->write("HTTP/1.1 200 OK\r\n");
            socket->write("Content-Type: text/html\r\n");
            socket->write("\r\n");
            socket->write(ch);
            socket->flush();
        }
    }
}


